import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from strategies.ml_enhanced_strategy import MLEnhancedStrategy
from optimization.strategy_optimizer import StrategyOptimizer
from data.market_data import MarketDataFetcher
from utils.config import Config

def main():
    # 加载配置
    config = Config()
    
    # 获取市场数据
    market_data_fetcher = MarketDataFetcher(
        exchange_id='okx',
        symbol='BTC/USDT',
        timeframe='1h'
    )
    
    # 获取过去30天的数据
    end_time = datetime.now()
    start_time = end_time - timedelta(days=30)
    market_data = market_data_fetcher.fetch_historical_data(
        start_time=start_time,
        end_time=end_time
    )
    
    # 定义参数网格
    param_grid = {
        'lookback_period': [12, 24, 48],
        'short_window': [5, 10, 20],
        'long_window': [20, 40, 60],
        'rsi_period': [7, 14, 21],
        'rsi_overbought': [70, 75, 80],
        'rsi_oversold': [20, 25, 30],
        'volatility_window': [20, 40],
        'position_size': [0.1, 0.2, 0.3],
        'stop_loss': [0.02, 0.03, 0.04],
        'take_profit': [0.04, 0.06, 0.08]
    }
    
    # 创建优化器
    optimizer = StrategyOptimizer(
        strategy_class=MLEnhancedStrategy,
        param_grid=param_grid,
        market_data=market_data
    )
    
    # 执行优化
    print("开始参数优化...")
    results = optimizer.optimize(n_jobs=-1)  # 使用所有可用CPU核心
    
    # 可视化结果
    optimizer.plot_optimization_results(metric='sharpe_ratio', top_n=10)
    
    # 获取最佳参数
    best_params = optimizer.get_best_params(metric='sharpe_ratio')
    print("\n最佳参数组合:")
    for param, value in best_params.items():
        print(f"{param}: {value}")
        
if __name__ == "__main__":
    main()
